package com.hanamaki.demo02;

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class Appium02 {
    static AndroidDriver<WebElement> driver;

    @BeforeMethod
    public void setUp() throws MalformedURLException {
//        1. 创建配置对象   new
        DesiredCapabilities cp = new DesiredCapabilities();
//          添加配置信息
        cp.setCapability("deviceName", "127.0.0.1:62001");
        cp.setCapability("platformName", "Android");
        cp.setCapability("appPackage", "com.handsgo.jiakao.android");
        cp.setCapability("appActivity", "com.handsgo.jiakao.android.splash.Login");
//        如何启动？
//        驱动 对象
        URL url = new URL("http://localhost:4723/wd/hub");
//        注册 需要打开的 驱动 以及url 以及 对应的软件
        driver = new AndroidDriver<>(url, cp);

        //       为 全局元素 添加  隐式等待时间  30
//        WebDriver.Timeouts timeouts = driver.manage().timeouts();
//        timeouts.implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void test() throws InterruptedException {

//        通过 ID的方式 点击  元素 点击  同意并继续
        WebElement elementById = driver.findElementById("com.handsgo.jiakao.android:id/btn_agree");
        elementById.click();
//        driver.findElement(By.id("com.handsgo.jiakao.android:id/btn_disagree"));

//        Thread.sleep(30000); // 浪费时间

//        显示等待 为某个元素
        WebDriverWait wait = new WebDriverWait(driver, 30, 1);

//         点击 不在提醒  com.handsgo.jiakao.android:id/permission_bg
        WebElement noClick = wait.until(new ExpectedCondition<WebElement>() {
            public WebElement apply(WebDriver input) {
                if (byElement(By.id("com.handsgo.jiakao.android:id/permission_box"))) {
                    return driver.findElement(By.id("com.handsgo.jiakao.android:id/permission_box"));
                } else {
                    return driver.findElement(By.id("com.handsgo.jiakao.android:id/permission_box"));
                }
            }
        });

        System.out.println(noClick.getText());

    }

    public static boolean byElement(By by) {
//         ctrl + alt +t
        try {
            driver.findElement(by);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @AfterMethod
    public void release() {
//        driver.quit();
    }

}
